package com.md.util;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;


public class RedisClient {

	private static Jedis jedis;//非切片客户端连接,用于单机redis
	private static JedisPool jedisPool;//非切片客户端连接池,用于单机redis
	
	private static final String REDIS_IP = ConfigReader.getConfig("redisIp");
	private static final Integer REDIS_PORT = ConfigReader.getInt("redisPort");
	private static final String REDIS_PASSWORD = ConfigReader.getConfig("redisPasswd");
	
	public static final String CACHE_PREFIX_APP = "redis_prefix_app_";
	public static final String CACHE_PREFIX_MCHNT = "redis_prefix_mchnt_";
	public static final String CACHE_PREFIX_WXAPP = "redis_prefix_wxapp_";
	public static final String CACHE_PREFIX_MCHNT_STL = "redis_prefix_mchnt_stl_";
	public static final String CACHE_PREFIX_SDKUSER = "redis_prefix_sdkuser_";
	public static final String CACHE_REGIST_SESSION = "redis_regist_session_";
	public static final String CACHE_FORGET_SESSION = "redis_forget_session_";
	public static final String CACHE_RESET_SESSION = "redis_reset_session_";
	public static final String CACHE_PROV_ALL = "redis_prov_all_";
	public static final String CACHE_PROV_ALL_MER = "redis_prov_all_mer_";
	public static final String CACHE_REGION_ALL = "redis_region_all_";
	public static final String CACHE_REGION_ALL_MER = "redis_region_all_mer_";
	public static final String CACHE_COUNTY_ALL = "redis_county_all_";
	public static final String CACHE_COUNTY_ALL_MER = "redis_county_all_mer_";
	public static final String CACHE_ROOTBANK_ALL = "redis_rootbank_all_";
	public static final String CACHE_PMSBANK_ALL = "redis_pmsbank_all_";
	public static final String CACHE_TAOBAO_IP = "redis_taobao_ip_";
	public static final String REDIS_CHANNEL_CONFIG_ ="redis_channel_config_";
	public static final String CACHE_BUSINESS_ALL = "redis_Business_all_";
	public static final String REDIS_QRCORD_TOKEN_ ="redis_qrcord_token_";
	public static final String REDIS_CH_FEE_ALLOT ="redis_ch_fee_allot_";
	
	public static final String CACHE_CHANNEL_CONFIG = "redis_channel_config_";
	
	
	public static final String AppId_By_MchId = "appId_by_mchid_";//应用ID与商户ID的对应值:appId_by_mchid_{mchid}
	public static final String Merchant_Billing="merchant_billing_";//商户能够调用各个类型的次数:merchant_billing_{mchid}_{type}
	public static final String Merchant_Billing_Complication="merchant_billing_complication_";//商户可以并发的次数merchant_billing_complication_{mchid}
	public static final String Merchant_Billing_Complication_List_="merchant_billing_complication_list_";//商户可以并发的次数merchant_billing_complication_{mchid}

	public static final String Merchant_Billing_Complication_Count="merchant_billing_complication_count_";//商户可以并发的次数merchant_billing_complication_count_{mchid}
	public static final String Merchant_Billing_Count ="merchant_billing_count_";//商户能够调用次数的总和appId_by_mchid_{mchid}
	
	public static final String CACHE_SECOND_PAY = "redis_second_pay_";
	
	public static final String Merchant_Billing_SUM = "merchant_billing_sum_";//商户调用次数统计key
	
	/**
	 * 初始化jedis连接池
	 */
	private static void initalPool() {
  
        JedisPoolConfig config = new JedisPoolConfig();  
        //设置最大连接数（100个足够用了，没必要设置太大）  
        config.setMaxTotal(100);  
        //最大空闲连接数  
        config.setMaxIdle(10);  
        //获取Jedis连接的最大等待时间（50秒）   
        config.setMaxWaitMillis(50 * 1000);  
        //在获取Jedis连接时，自动检验连接是否可用  
        config.setTestOnBorrow(false);  
        //在将连接放回池中前，自动检验连接是否有效  
        config.setTestOnReturn(true);  
        //自动测试池中的空闲连接是否都是可用连接  
        config.setTestWhileIdle(true);
		
		jedisPool = new JedisPool(config,REDIS_IP,REDIS_PORT,50 * 1000,REDIS_PASSWORD);

	}
	
	/** 
     * 获取Jedis实例 
     */  
    private static Jedis getJedis() {  
        if (null == jedisPool) {  
        	initalPool();  
        }
        
        int timeoutCount = 0;  
        while (true) {  
            try {  
                if (null != jedisPool) {
                	LogWriter.info("jedisInfo ... NumActive=" + jedisPool.getNumActive()  
                    + ", NumIdle=" + jedisPool.getNumIdle()  
                    + ", NumWaiters=" + jedisPool.getNumWaiters()  
                    + ", isClosed=" + jedisPool.isClosed());
                    Jedis jedis = jedisPool.getResource();
                    jedis.auth(REDIS_PASSWORD);
                    return jedis;  
                }
                
                
                
            } catch (Exception e) {  
                if (e instanceof JedisConnectionException) {  
                    timeoutCount++;  
                    LogWriter.warn("getJedis timeoutCount=[" + timeoutCount + "]");  
                    if (timeoutCount > 10) {  
                        break;  
                    }  
                } else {  
                	break;  
                } 
                LogWriter.error("GetJedis error,", e);
            }  
        }  
        return null; 
    }    
	
    /** 
     * 释放Jedis资源 
     * 
     * @param jedis 
     */  
    public static void returnResource(Jedis jedis) {  
        if (null != jedis) {  
        	jedis.close();
        }  
    }
    
    
    /**
     * 安全取得redis连接
     * @param key redis key
     * @return
     */
	public synchronized static String getByKey(String key){
		Jedis jedis = getJedis();  
        if (null == jedis) {  
            return "";  
        } 
        String value = jedis.get(key);  
        returnResource(jedis);  
        return value;
	}
	/**
	 * 
	 * @param key   redis key
	 * @param value redis value
	 * @return
	 */
	public synchronized static String set(String key,String value){
		Jedis jedis = getJedis();  
  
        if (null == jedis) {  
            return "";  
        }
        String result = jedis.set(key, value);  
        returnResource(jedis);
        return result;
	}
	
	public synchronized static Long del(String key){
		Jedis jedis = getJedis();  
  
        if (null == jedis) {  
            return null;  
        }
        Long delValue = jedis.del(key);
        returnResource(jedis);
        return delValue;
	}
	
	/**
	 * 安全验证redis key
	 * @param key
	 * @return
	 */
	public synchronized static Boolean exisit(String key){
		Jedis jedis = getJedis();  
  
        if (null == jedis) {  
            return false;  
        } 
        boolean result = jedis.exists(key); 
        returnResource(jedis);
        return result;
	}
	public static void main(String[] args) {
		System.out.println(jedis.del(CACHE_PREFIX_SDKUSER+"448020995@qq.com"));
		System.out.println(jedis.del(CACHE_PREFIX_MCHNT+"0000000022"));
		System.out.println(1);
	}
}